using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ServerLogicDll;
using System.Net;
using MsgLogic;

namespace ChatServerApp
{
    public partial class ChatServerAppForm : Form
    {
        private Server chatServer;
        private bool continueRunning;

        public ChatServerAppForm()
        {
            InitializeComponent();
            chatServer = null;
            continueRunning = false;
            toolStripStatus.Text = "Server Offline";
            toolStripStatus.ForeColor = Color.Red;
        }

        private void menuItemStart_Click(object sender, EventArgs e)
        {
            
            ServerProperties dialog = new ServerProperties();
            DialogResult dr = dialog.ShowDialog();
            if (dr == DialogResult.OK)
            {
                if (chatServer == null)
                {

                    //TODO: try catch on the ip address
                    chatServer = new Server(IPAddress.Parse(dialog.txtIpAddress.Text), Int32.Parse(dialog.numericUpDownPort.Value.ToString()));
                    chatServer.DisconnectClient += new EventHandler<ClientDisonnectEventArgs>(chatServer_DisconnectClient);
                    chatServer.NewClientConnected += new EventHandler<ClientConnectedEventArgs>(chatServer_NewClientConnected);
                    lock (this)
                    {
                        continueRunning = true;
                    }
                    chatServer.StartListen(backgroundWorker1);
                    //backgroundWorker1.RunWorkerAsync();

                    toolStripStatus.Text = "Server Online";
                    toolStripStatus.ForeColor = Color.Green;

                }
                //MessageBox.Show(dialog.txtIpAddress.Text + ":" + dialog.numericUpDownPort.Value);
            }
            //else
            //    MessageBox.Show("Cancel");
        }

        void chatServer_NewClientConnected(object sender, ClientConnectedEventArgs e)
        {
          //  System.Threading.Thread.Sleep(5000);
            
            //MessageBox.Show(e.UserName + " has just connected");

            //here i'll report progress to update the gui 1- client connected

            
            backgroundWorker1.ReportProgress(1, e.UserName);
            //ListViewItem item = new ListViewItem(e.UserName);
            //listViewCurrentUsers.Items.Insert(0, item);


        }

        void chatServer_DisconnectClient(object sender, ClientDisonnectEventArgs e)
        {
            //MessageBox.Show(e.UserName + " has just disconnected");

            //here i'll report progress to update the gui 0- client disconnected
            backgroundWorker1.ReportProgress(0, e.UserName);
        }

        private void menuItemStop_Click(object sender, EventArgs e)
        {
            if (chatServer != null)
            {
                lock (this)
                {
                    continueRunning = false;
                }
                chatServer.StopListen(backgroundWorker1);
                chatServer.DisconnectClient -= new EventHandler<ClientDisonnectEventArgs>(chatServer_DisconnectClient);
                chatServer.NewClientConnected -= new EventHandler<ClientConnectedEventArgs>(chatServer_NewClientConnected);
                //chatServer.ClientsList.Clear();
                chatServer = null;
                listViewHistory.Items.Clear();
                listViewCurrentUsers.Items.Clear();
                this.Text = "Chat Server Admin";
                toolStripStatus.Text = "Server Offline";
                toolStripStatus.ForeColor = Color.Red;
            }
            
        }

        //private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    while (continueRunning)
        //    {
        //        System.Threading.Thread.Sleep(2000);
        //    }
        //    //ServerProperties dialog = new ServerProperties();
        //    //DialogResult dr = dialog.ShowDialog();
        //    //if (dr == DialogResult.OK)
        //    //{
        //    //    if (chatServer == null)
        //    //    {
        //    //        chatServer = new Server(IPAddress.Parse(dialog.txtIpAddress.Text), Int32.Parse(dialog.numericUpDownPort.Value.ToString()));
        //    //        chatServer.DisconnectClient += new EventHandler<ClientDisonnectEventArgs>(chatServer_DisconnectClient);
        //    //        chatServer.NewClientConnected += new EventHandler<ClientConnectedEventArgs>(chatServer_NewClientConnected);
        //    //        //chatServer.StartListen();
        //    //        //System.Threading.Thread.Sleep(30000);
        //    //    }
        //    //}

        //}

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
           
            if (e.ProgressPercentage == 1)
            {
                //update gui that new client connected
                //ListViewItem item = new ListViewItem((string)e.UserState);
                //listViewCurrentUsers.Items.Add(item);
                ListViewItem item = new ListViewItem();

                item.SubItems[0].Text = (string)e.UserState;
                item.SubItems.Add("Connected");
                item.SubItems.Add(DateTime.Now.ToString());
                
                listViewCurrentUsers.Items.Insert(0, item);
                
                ListViewItem historyItem = new ListViewItem();
                historyItem = (ListViewItem)item.Clone();
                listViewHistory.Items.Insert(0, historyItem);

                this.Text = "Chat Server Admin - " + listViewCurrentUsers.Items.Count + " Connected Clients";

                //MessageBox.Show((string)e.UserState + " has just connected");
            }
            else if (e.ProgressPercentage == 0)
            {
                //update gui that client disconnected
                for (int i = 0; i < listViewCurrentUsers.Items.Count; i++ )
                {
                    if (listViewCurrentUsers.Items[i].SubItems[0].Text == (string)e.UserState)
                    {
                    //    chatServer.RemoveClient((string)e.UserState);
                        listViewCurrentUsers.Items.RemoveAt(i);

                        ListViewItem disconnectedItem = new ListViewItem();

                        disconnectedItem.SubItems[0].Text = (string)e.UserState;
                        disconnectedItem.SubItems.Add("Disconnected");
                        disconnectedItem.SubItems.Add(DateTime.Now.ToString());

                        listViewHistory.Items.Insert(0, disconnectedItem);

                        this.Text = "Chat Server Admin - " + listViewCurrentUsers.Items.Count + " Connected Clients";
						//chatServer.RemoveClient(e.UserState.ToString());
                    }
                }
            }
        }

        private void disconnectUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string userName = listViewCurrentUsers.SelectedItems[0].SubItems[0].Text;
                TextMsg txt = new TextMsg("Server", userName + " disconnected", Color.Black);
                chatServer.RemoveClient(userName);
                //chatServer.OnClientDisconnect(userName);
                chatServer.SendAllClients(txt);

            }
            catch (Exception)
            {

            }

        }
    }
}